﻿using MediatR;
using Traceability.Commont.Domains.BatchManagementFiles;
using Traceability.Commont.Domains.ScratchTheFat;
using Traceability.Commont.DTOs.CommontFiles;
using Traceability.Commont.DTOs.WhiteStripWeighingHtmlGroup;
using Traceability.Commont.Infrastructures.Interfaces;

namespace U.Enterprise.Api.Applications.SalesWeighings
{
    public class WeighTheFatGroupHander : IRequestHandler<WeighTheFatGroupCommand, Resqults<WeighTheFatGroupList>>
    {
        private readonly IBateRepository<BulkSlaughter> bulk;
        private readonly IBateRepository<WeighTheFat> weight;

        public WeighTheFatGroupHander(IBateRepository<BulkSlaughter> bulk, IBateRepository<WeighTheFat> weight)
        {
            this.bulk = bulk;
            this.weight = weight;
        }

        public async Task<Resqults<WeighTheFatGroupList>> Handle(WeighTheFatGroupCommand request, CancellationToken cancellationToken)
        {
            try
            {
                Resqults<WeighTheFatGroupList> res = new Resqults<WeighTheFatGroupList>();
                int years = DateTime.Now.Year;
                int months = DateTime.Now.Month;
                if (request.Date != null)
                {
                    years = request.Date.Value.Year;
                    months = request.Date.Value.Month;
                }
                var info = (from a in bulk.GetAll()
                            join b in weight.GetAll() on a.BulkSlaughterNo equals b.BulkSlaughterNo
                            where (b.WeighTime.Year == years && b.WeighTime.Month == months)
                            group new { a, b } by new { b.WeighTime.Day } into c
                            select new WeighTheFatGroupList()
                            {
                                SlaughterNum = c.Sum(x => x.a.BulkSlaughterNum),
                                WeighNum = c.Sum(x => x.b.WeightNum),
                                TotalWeight = c.Sum(x => x.b.WeightNum*x.b.AverageWeight),
                                Day=c.Key.Day
                            }).ToList();
                res.Date = info;
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
